package com.example.block_chain.utils.node;

import com.alibaba.fastjson2.JSONObject;
import com.example.block_chain.domain.pojo.Student;
import lombok.extern.slf4j.Slf4j;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

/*
 *@description: Post请求工具
 *@author: hisen
 *@Time: 2024/3/7  14:16
 */
@Slf4j
public class PostRequestUtil {

    public static void sendBatchSaveStudentPostRequest(String targetURL, List<StudentNodePostBody> postBody) {
        HttpURLConnection connection = null;

        try {
            URL url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setDoOutput(true);

            String jsonInputString = JSONObject.toJSONString(postBody);

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                log.info(responseCode + ":: " + connection.getResponseMessage());
            } else {
                log.error(responseCode + ":: " + connection.getResponseMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    public static List<StudentNodePostBody> getStudentNodes(List<Student> students) {
        return students.stream().map(student ->
        {
            if (student != null) {
                return new StudentNodePostBody(student.getId().toString(), student.getSName(), student.getSGrade());
            }
            return null;
        }).collect(Collectors.toList());
    }
}
